from django import forms
from django.core.validators import RegexValidator
# ValidationError 是 Django 表单系统中用于表单数据验证失败时抛出的异常。
from django.core.exceptions import ValidationError
from sa import models
from sa.forms.bootstrap import BootStrapForm
# 导入加密工具
from Utils import encrypt
import re
from django.shortcuts import render, HttpResponse, redirect


class LoginForm(BootStrapForm, forms.Form):
    emp_no = forms.CharField(label='员工号',
                             validators=[RegexValidator(regex=r'^\b\d{1,5}\b',
                                                        message='只需输入FBCN后的5位数字！')])
    # render_value=True 刷新后保留密码
    pwd = forms.CharField(label='密码', widget=forms.PasswordInput(render_value=True))
    code = forms.CharField(label='图片验证码')

    # 重写构造函数 增加 request,因为后面要从 request.session中获取信息
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request  # 增加 self.request 属性，需要传入

    def clean_pwd(self):
        txt_pwd = self.cleaned_data.get('pwd')
        # if txt_pwd == 'x-admin':
        #     raise ValidationError('禁止使用默认密码 "x-admin"，请更改您的密码。')
        return encrypt.md5(txt_pwd)
        # return txt_pwd

    def clean_code(self):
        txt_code = self.cleaned_data['code']
        # 从 session 中获取验证码,使用get获取 ，因为可能不存在
        session_code = self.request.session.get('image_code')
        if not session_code:
            raise ValidationError('验证码过期或者不存在,请重新获取！')
        # .strip() 去除字符串的前和尾随空白字符
        # .upper() 转大写， 大小写不敏感
        if txt_code.strip().upper() != session_code.strip().upper():
            raise ValidationError('验证码错误!')
        return txt_code


class ChangePasswordForm(BootStrapForm, forms.Form):
    old_pwd = forms.CharField(label='旧密码', widget=forms.PasswordInput(render_value=True))
    new_pwd = forms.CharField(label='新密码', widget=forms.PasswordInput())
    confirm_pwd = forms.CharField(label='确认密码', widget=forms.PasswordInput())

    # 重写构造函数 增加 request,
    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_old_pwd(self):
        old_pwd = encrypt.md5(self.cleaned_data.get('old_pwd'))
        if old_pwd != self.request.sa.Password:
            raise ValidationError('现有密码不正确')
        return old_pwd

    def clean_new_pwd(self):
        new_pwd = self.cleaned_data.get('new_pwd')
        import re
        pwd_pattern = r'^[A-Za-z0-9]{4,12}$'
        if re.match(pwd_pattern, new_pwd):
            return new_pwd
        raise ValidationError('密码要求4-12位的字母和数字')

    def clean_confirm_pwd(self):
        new_pwd = self.cleaned_data.get('new_pwd')
        confirm_pwd = self.cleaned_data.get('confirm_pwd')
        if new_pwd == confirm_pwd:
            return confirm_pwd
        else:
            raise ValidationError('密码不匹配！')








